// extract module
var connect = require('connect');
var socketio = require('socket.io');
var fs = require('fs');

var seats = [
    [1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1],
    [1, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1]
];

// create web server
var server = connect.createServer(connect.router(function(app) {
	app.get('/', function(request, response, next) {
		fs.readFile('./resources/booking.html', function(error, data) {
			response.writeHead(200, {'Content-Type': 'text/html'});
			response.end(data);
		});
	});
	
	app.get('/seats', function(request, response, next) {
		response.writeHead(200, {'Content-Type': 'application/json'});
		response.end(JSON.stringify(seats));
	});
}));

// run server
server.listen(52273, function() {
	console.log('Server running at http://localhost:52273');
});

// create and run socket server
var io = socketio.listen(server);
io.set('log level', 2);
io.sockets.on('connection', function(socket) {
	// reserve event handler
	socket.on('reserve', function(data) {
		seats[data.x][data.y] = 2;
		io.sockets.emit('reserve', data);
	});
});